<?php
/**
 * FilialClienteList Listing
 * @author  <your name here>
 */
class FilialClienteList extends TPage
{
    private $form;     // registration form
    private $datagrid; // listing
    private $pageNavigation;
    private $loaded;
    
    /**
     * Class constructor
     * Creates the page, the form and the listing
     */
    public function __construct()
    {
        parent::__construct();
        
        // creates the form
        $this->form = new TForm('form_search_FilialCliente');
        $this->form->class = 'tform'; // CSS class
        
        // creates a table
        $table = new TTable;
        $table-> width = '100%';
        $this->form->add($table);
        
        // add a row for the form title
        $row = $table->addRow();
        $row->class = 'tformtitle'; // CSS class
        $row->addCell( new TLabel('Consulta de Filiais') )->colspan = 2;
        

        // create the form fields
        $id_cliente          = new TDBSeekButton('id_cliente', 'permission', 'form_search_FilialCliente', 'Cliente', 'apelido', 'id_cliente', 'nome_cliente');
        $nome_cliente        = new TEntry('nome_cliente');               

        $id_filial_cliente              = new TEntry('id_filial_cliente');
        $razao_social                   = new TEntry('razao_social');
        $tipo_filial                    = new TCombo('tipo_filial');
        $tipo_inscricao                 = new TCombo('tipo_inscricao');
        $num_inscricao                  = new TEntry('num_inscricao');


        // define the sizes
        $id_cliente->setSize(40);
        $id_filial_cliente->setSize(40);
        $razao_social->setSize(200);
        $tipo_filial->setSize(200);
        $tipo_inscricao->setSize(100);
        $num_inscricao->setSize(200);
        $nome_cliente->setEditable(false);     
           
        $tipo_inscricao->addItems(array(1=>'CNPJ', 2=>'CEI', 3=>'CPF'));
        $tipo_filial->addItems(array('M'=>'Matriz','F'=>'Filial','O'=>'Obra','T'=>'Temporária','C'=>'Cooperativa de Trabalho', 'D'=>'Trabalhador Doméstico'));


        // add one row for each form field
        $table->addRowSet( new TLabel('Cliente:'), array($id_cliente, $nome_cliente));
        $table->addRowSet( new TLabel('ID:'), $id_filial_cliente );
        $table->addRowSet( new TLabel('Razão Social:'), $razao_social );
        $table->addRowSet( new TLabel('Tipo de Filial:'), $tipo_filial );
        $table->addRowSet( new TLabel('Tipo Inscrição:'), $tipo_inscricao );
        $table->addRowSet( new TLabel('Nº Inscrição:'), $num_inscricao );


        $this->form->setFields(array($id_cliente,$id_filial_cliente,$razao_social,$tipo_filial,$tipo_inscricao,$num_inscricao));


        // keep the form filled during navigation with session data
        $this->form->setData( TSession::getValue('FilialCliente_filter_data') );
        
        // create two action buttons to the form
        $find_button = TButton::create('find', array($this, 'onSearch'), _t('Find'), 'ico_find.png');
        $new_button  = TButton::create('new',  array('FilialClienteForm', 'onEdit'), _t('New'), 'ico_new.png');
        
        $this->form->addField($find_button);
        $this->form->addField($new_button);
        
        $buttons_box = new THBox;
        $buttons_box->add($find_button);
        $buttons_box->add($new_button);
        
        // add a row for the form action
        $row = $table->addRow();
        $row->class = 'tformaction'; // CSS class
        $row->addCell($buttons_box)->colspan = 2;
        
        // creates a Datagrid
        $this->datagrid = new TDataGrid;
        $this->datagrid->setHeight(320);
        

        // creates the datagrid columns
        $id_filial_cliente   = new TDataGridColumn('id_filial_cliente', 'ID', 'right', 40);
        $razao_social   = new TDataGridColumn('razao_social', 'Razão Social', 'left', 300);
        $tipo_filial   = new TDataGridColumn('tipo_filial', 'Tipo de Filial', 'left', 100);
        $nome_cliente   = new TDataGridColumn('nome_cliente', 'Cliente', 'left', 300);
        $tipo_inscricao   = new TDataGridColumn('tipo_inscricao', 'Tipo Inscr', 'right', 100);
        $num_inscricao   = new TDataGridColumn('num_inscricao', 'Nº Inscrição', 'left', 200);


        // add the columns to the DataGrid
        $this->datagrid->addColumn($id_filial_cliente);
        $this->datagrid->addColumn($razao_social);
        $this->datagrid->addColumn($tipo_filial);
        $this->datagrid->addColumn($nome_cliente);
        $this->datagrid->addColumn($tipo_inscricao);
        $this->datagrid->addColumn($num_inscricao);


        // creates the datagrid column actions
        $order_nome_cliente= new TAction(array($this, 'onReload'));
        $order_nome_cliente->setParameter('order', 'nome_cliente');
        $nome_cliente->setAction($order_nome_cliente);

        $order_id_filial_cliente= new TAction(array($this, 'onReload'));
        $order_id_filial_cliente->setParameter('order', 'id_filial_cliente');
        $id_filial_cliente->setAction($order_id_filial_cliente);

        $order_razao_social= new TAction(array($this, 'onReload'));
        $order_razao_social->setParameter('order', 'razao_social');
        $razao_social->setAction($order_razao_social);


        
        // creates two datagrid actions
        $action1 = new TDataGridAction(array('FilialClienteForm', 'onEdit'));
        $action1->setLabel(_t('Edit'));
        $action1->setImage('ico_edit.png');
        $action1->setField('id_filial_cliente');
        
        $action2 = new TDataGridAction(array($this, 'onDelete'));
        $action2->setLabel(_t('Delete'));
        $action2->setImage('ico_delete.png');
        $action2->setField('id_filial_cliente');
        
        // add the actions to the datagrid
        $this->datagrid->addAction($action1);
        $this->datagrid->addAction($action2);
        
        // create the datagrid model
        $this->datagrid->createModel();
        
        // creates the page navigation
        $this->pageNavigation = new TPageNavigation;
        $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
        $this->pageNavigation->setWidth($this->datagrid->getWidth());
        
        TScript::create('setTimeout(function() { $("input[name=\'id_filial_cliente\']").focus() }, 500);');
        
        // create the page container
        $container = TVBox::pack( $this->form, $this->datagrid, $this->pageNavigation);
        parent::add($container);
    }
    
    /**
     * method onInlineEdit()
     * Inline record editing
     * @param $param Array containing:
     *              key: object ID value
     *              field name: object attribute to be updated
     *              value: new attribute content 
     */
    function onInlineEdit($param)
    {
        try
        {
            // get the parameter $key
            $field = $param['field'];
            $key   = $param['key'];
            $value = $param['value'];
            
            TTransaction::open('permission'); // open a transaction with database
            $object = new FilialCliente($key); // instantiates the Active Record
            $object->{$field} = $value;
            $object->store(); // update the object in the database
            TTransaction::close(); // close the transaction
            
            $this->onReload($param); // reload the listing
            new TMessage('info', "Record Updated");
        }
        catch (Exception $e) // in case of exception
        {
            new TMessage('error', '<b>Error</b> ' . $e->getMessage()); // shows the exception error message
            TTransaction::rollback(); // undo all pending operations
        }
    }
    
    /**
     * method onSearch()
     * Register the filter in the session when the user performs a search
     */
    function onSearch()
    {
        // get the search form data
        $data = $this->form->getData();
        
        // clear session filters
        TSession::setValue('FilialClienteList_filter_id_cliente',   NULL);
        TSession::setValue('FilialClienteList_filter_id_filial_cliente',   NULL);
        TSession::setValue('FilialClienteList_filter_razao_social',   NULL);
        TSession::setValue('FilialClienteList_filter_tipo_filial',   NULL);
        TSession::setValue('FilialClienteList_filter_tipo_inscricao',   NULL);
        TSession::setValue('FilialClienteList_filter_num_inscricao',   NULL);

        if (isset($data->id_cliente) AND ($data->id_cliente)) {
            $filter = new TFilter('id_cliente', 'like', "%{$data->id_cliente}%"); // create the filter
            TSession::setValue('FilialClienteList_filter_id_cliente',   $filter); // stores the filter in the session
        }


        if (isset($data->id_filial_cliente) AND ($data->id_filial_cliente)) {
            $filter = new TFilter('id_filial_cliente', 'like', "%{$data->id_filial_cliente}%"); // create the filter
            TSession::setValue('FilialClienteList_filter_id_filial_cliente',   $filter); // stores the filter in the session
        }


        if (isset($data->razao_social) AND ($data->razao_social)) {
            $filter = new TFilter('razao_social', 'like', "%{$data->razao_social}%"); // create the filter
            TSession::setValue('FilialClienteList_filter_razao_social',   $filter); // stores the filter in the session
        }


        if (isset($data->tipo_filial) AND ($data->tipo_filial)) {
            $filter = new TFilter('tipo_filial', 'like', "%{$data->tipo_filial}%"); // create the filter
            TSession::setValue('FilialClienteList_filter_tipo_filial',   $filter); // stores the filter in the session
        }


        if (isset($data->tipo_inscricao) AND ($data->tipo_inscricao)) {
            $filter = new TFilter('tipo_inscricao', 'like', "%{$data->tipo_inscricao}%"); // create the filter
            TSession::setValue('FilialClienteList_filter_tipo_inscricao',   $filter); // stores the filter in the session
        }


        if (isset($data->num_inscricao) AND ($data->num_inscricao)) {
            $filter = new TFilter('num_inscricao', 'like', "%{$data->num_inscricao}%"); // create the filter
            TSession::setValue('FilialClienteList_filter_num_inscricao',   $filter); // stores the filter in the session
        }

        
        // fill the form with data again
        $this->form->setData($data);
        
        // keep the search data in the session
        TSession::setValue('FilialCliente_filter_data', $data);
        
        $param=array();
        $param['offset']    =0;
        $param['first_page']=1;
        $this->onReload($param);
    }
    
    /**
     * method onReload()
     * Load the datagrid with the database objects
     */
    function onReload($param = NULL)
    {
        try
        {
            // open a transaction with database 'permission'
            TTransaction::open('permission');
            
            // creates a repository for FilialCliente
            $repository = new TRepository('FilialCliente');
            $limit = 10;
            // creates a criteria
            $criteria = new TCriteria;
            
            // default order
            if (empty($param['order']))
            {
                $param['order'] = 'id_filial_cliente';
                $param['direction'] = 'asc';
            }
            $criteria->setProperties($param); // order, offset
            $criteria->setProperty('limit', $limit);
            

            if (TSession::getValue('FilialClienteList_filter_id_cliente')) {
                $criteria->add(TSession::getValue('FilialClienteList_filter_id_cliente')); // add the session filter
            }


            if (TSession::getValue('FilialClienteList_filter_id_filial_cliente')) {
                $criteria->add(TSession::getValue('FilialClienteList_filter_id_filial_cliente')); // add the session filter
            }


            if (TSession::getValue('FilialClienteList_filter_razao_social')) {
                $criteria->add(TSession::getValue('FilialClienteList_filter_razao_social')); // add the session filter
            }


            if (TSession::getValue('FilialClienteList_filter_tipo_filial')) {
                $criteria->add(TSession::getValue('FilialClienteList_filter_tipo_filial')); // add the session filter
            }


            if (TSession::getValue('FilialClienteList_filter_tipo_inscricao')) {
                $criteria->add(TSession::getValue('FilialClienteList_filter_tipo_inscricao')); // add the session filter
            }


            if (TSession::getValue('FilialClienteList_filter_num_inscricao')) {
                $criteria->add(TSession::getValue('FilialClienteList_filter_num_inscricao')); // add the session filter
            }

            
            // load the objects according to criteria
            $objects = $repository->load($criteria, FALSE);
            
            $this->datagrid->clear();
            if ($objects)
            {
                // iterate the collection of active records
                foreach ($objects as $object)
                {
                    // add the object inside the datagrid
                    $this->datagrid->addItem($object);
                }
            }
            
            // reset the criteria for record count
            $criteria->resetProperties();
            $count= $repository->count($criteria);
            
            $this->pageNavigation->setCount($count); // count of records
            $this->pageNavigation->setProperties($param); // order, page
            $this->pageNavigation->setLimit($limit); // limit
            
            // close the transaction
            TTransaction::close();
            $this->loaded = true;
        }
        catch (Exception $e) // in case of exception
        {
            // shows the exception error message
            new TMessage('error', '<b>Error</b> ' . $e->getMessage());
            
            // undo all pending operations
            TTransaction::rollback();
        }
    }
    
    /**
     * method onDelete()
     * executed whenever the user clicks at the delete button
     * Ask if the user really wants to delete the record
     */
    function onDelete($param)
    {
        // define the delete action
        $action = new TAction(array($this, 'Delete'));
        $action->setParameters($param); // pass the key parameter ahead
        
        // shows a dialog to the user
        new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
    }
    
    /**
     * method Delete()
     * Delete a record
     */
    function Delete($param)
    {
        try
        {
            $key=$param['key']; // get the parameter $key
            TTransaction::open('permission'); // open a transaction with database
            $object = new FilialCliente($key, FALSE); // instantiates the Active Record
            $object->delete(); // deletes the object from the database
            TTransaction::close(); // close the transaction
            $this->onReload( $param ); // reload the listing
            new TMessage('info', TAdiantiCoreTranslator::translate('Record deleted')); // success message
        }
        catch (Exception $e) // in case of exception
        {
            new TMessage('error', '<b>Error</b> ' . $e->getMessage()); // shows the exception error message
            TTransaction::rollback(); // undo all pending operations
        }
    }
    
    /**
     * method show()
     * Shows the page
     */
    function show()
    {
        // check if the datagrid is already loaded
        if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
        {
            $this->onReload( func_get_arg(0) );
        }
        parent::show();
    }
}
